import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class DNSServer implements Runnable{
	private static final int PORT = 25252;
	private static final int MAX = 1024;
	private DatagramSocket serverSocket;
	private DNSDatabase database;
	
	public static void main(String args[]){
		new Thread(new DNSServer()).start();
	}

	public DNSServer() {
		try {
			serverSocket = new DatagramSocket(PORT);
			database = DNSDatabase.databaseGenerator();
			System.out.println("DNS Server avviato");
		} catch (SocketException e) {
			System.out
					.println("Impossibile avviare il server. Probabilemente la porta è occupata o il server è già attivo.");
		}
	}

	@Override
	public void run() {
		if(serverSocket!=null)
		{
			while(true)
			{
				byte [] receiveData=new byte[MAX];
				DatagramPacket receivePacket = new DatagramPacket(
						receiveData, receiveData.length);
				try {
					serverSocket.receive(receivePacket);
					
					//Avvio il thread che gestisce la risposta
					new DNSRequestHandler(database, receivePacket).start();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		
	}
}
